<?php

namespace app\member\controller;

use think\facade\Session;
use think\Db;
use app\pay\controller\Payhqdf;
class Profit extends Base
{
	/**
	 * 分润报表
	 */
	public function Index()
	{
		//今日消费金额
		$list = Db::name('Agent')->where('agent_pid', session::get('agent_id'))->select();
		// dump($list);die;
		$date = getTree($list, session::get('agent_id'), 'agent_pid', 'agent_id');
		dump($date);
		die;
		// return view();
	}

	/**
	 * 分润提现
	 */
	public function Putforward()
	{
		$uid = session::get('member_id');//halt($uid);
		$user = Db::name("user")->field("user_moeny")->find($uid);
		//个人的银行卡信息
		$bank = Db::name('user_card as a')
			->join('BankList b', 'a.card_bank_id=b.list_id')
			->field('a.card_id,a.card_branch,b.list_name')
			->where(['a.card_uid' => $uid, "a.card_type" => 2])
			->select();
		if ($this->request->isPost()) {
			$money = input('post.money');
			if (empty($money)) {
				return json(['error' => 1, 'msg' => '提现金额']);
			}

			if ($money < 10) {
				return json(['error' => 1, 'msg' => '提现金额必须大于10']);
			}

			if ($money % 1) {
				return json(['error' => 1, 'msg' => '提现金额必须是整数']);
			}

			if ($money > $user["user_moeny"]) {
				return json(['error' => 1, 'msg' => '提现余额不足']);
			}
			$profit_rate = 2;
			//$rate = 0.0615;
			$rate = 0.06;
			$true_money = blxsd($money * (1 - $rate)-$profit_rate,2);
			$data = [];



			$result = Db::name('UserProfit')->where(['profit_type' => 1])->find();
			if (empty($result)) {
				$data["profit_uid"] = $uid;
				$data["profit_card_id"] = $bank[0]["card_id"];
				$data["profit_form_no"] = get_order_sn("T", $uid);
				$data["profit_money"] = $money;
				$data["profit_true_money"] = $true_money;
				$data["profit_rate"] = $profit_rate;
				$data["profit_type"] = 1;
				$data["profit_time"] = time();
				$data["frozenamount"] = round($true_money*0.0015+0.5);
				$res = Db::name('UserProfit')->insertGetId($data);
				if ($res) {
					//扣款
					Db::name("user")->where(["user_id"=>$uid])->setDec("user_moeny",$money);
					//调用代付接口
					$res = (new Payhqdf)->pay($res);
					//var_dump($res);
					if(!isset($res["errtext"]) || empty($res["errtext"])){
						return json(['error' => 0, 'msg' => '提现成功，已到账']);
					}else{
						return json(['error' => 0, 'msg' => '提交成功,到账情况：'.$res["errtext"]]);
					}
				} else {
					return json(['error' => 1, 'msg' => '提交失败']);
				}
			}else{
				return json(["error"=>1,"msg"=>"有未处理的提现订单,不能继续提现"]);
			}
		} else {
			$this->assign('bank', $bank[0]);
			$this->assign('user', $user);
			return view();
		}
	}

	/**
	 * 下级分润表报
	 */
	public function underlevelrun()
	{
		$get = input('get.');

		if ($get['pid']) {
			$pid = $get['pid'];
		} else {
			$pid = session::get('member_id');
		}
		// 获取下级关系代理
		// $proagent = $this->getagentSubs(session::get('agent_id'));

		if ($get['account']) {
			$where[] = array('user_account', 'like', '%' . $get['account'] . "%");
			$whereor[] = array('user_name', 'like', '%' . $get['account'] . "%");
		}
		$list = Db::name('user')
			->field('user_id')
			->where(['user_pid' => $pid])
			->where($where)
			->whereOr($whereor)
			->paginate(10, false, ['query' => $get]);

		$arrs = [];
		foreach ($list as $k => $v) {
			$v = $v['user_id'];
			$pid = $this->getAgs($v, 'user_pid');
			if ($pid == session::get('member_id')) {
				$userinfo = '[直]' . $this->getAgs($v, 'user_account') . '[' . $this->getAgs($v, 'user_name') . ']';
			} else {
				$userinfo = $this->getAgs($v, 'user_account') . '[' . $this->getAgs($v, 'user_name') . ']';
			}

			$arrs['id'] = $v;
			$arrs['aginfo'] = $userinfo;
			$arrs['agsuper'] = $this->getAgs($pid, 'user_account') . '--' . $this->getAgs($pid, 'user_name');

			$where = array('blog_user'=>$pid,'blog_touser' => $v);
			$arrs['couopens'] = Db::name('user_bonuslog')
				->where($where)
				->count('blog_id'); // 订单笔数

			$arrs['couamount'] = Db::name('user_bonuslog')
				->where($where)
				->sum('blog_money'); // 总金额

			$arrs['skcoufenrun'] = Db::name('user_bonuslog')
				->where(['blog_type' => 2])
				->where($where)
				->sum('blog_money'); // 总收款分润

			$arrs['hkcoufenrun'] = Db::name('user_bonuslog')
				->where(['blog_type' => 3])
				->where($where)
				->sum('blog_money'); // 总还款分润
			$arrs['sjcoufenrun'] = Db::name('user_bonuslog')
				->where(['blog_type' => 1])
				->where($where)
				->sum('blog_money'); // 总升级分润

			$arrs['coufenrun'] = Db::name('user_bonuslog')
				->where($where)
				->sum('blog_money'); // 总分润

			$agop = Db::name('user')->where(['user_pid' => $v])->find();
			if ($agop) {
				$arrs['agop'] = 'yeval';
			} else {
				$arrs['agop'] = 'noeval';
			}

			// 今日总金额
			$todymoney += Db::name('user_bonuslog')
				->where('blog_time', '>', strtotime(date("Y-m-d"), time()))
				->where('blog_touser', $v)
				->sum('blog_money');
			// 今日分润金额
			$todyprofit += Db::name('user_bonuslog')
				->where('blog_time', '>', strtotime(date("Y-m-d"), time()))
				->where('blog_touser', $v)
				->sum('blog_money');
			// 总金额
			$sunmoney += $arrs['couamount'];
			// 总分润
			$sunprofit += $arrs['coufenrun'];

			$list->offsetSet($k, $arrs);
		}
		$todymoney = $todymoney ? $todymoney : 0;
		$todyprofit = $todyprofit ? $todyprofit : 0;
		$sunmoney = $sunmoney ? $sunmoney : 0;
		$sunprofit = $sunprofit ? $sunprofit : 0;

		$this->assign('todymoney', $todymoney);
		$this->assign('todyprofit', $todyprofit);
		$this->assign('sunmoney', $sunmoney);
		$this->assign('sunprofit', $sunprofit);
		$this->assign('getdata', $get);
		$this->assign('list', $list);
		return view();
	}

	// 分润明细
	public function fenrunfine()
	{

		$keywords = input('get.');
		if (!$keywords['pid']) {
			return json(['error' => 1, 'msg' => '参数错误']);
		}

		if (isset($keywords) && !empty($keywords)) {
			$map = [];
			$map = $this->getwheres($keywords);
		}
		$pid = $keywords['pid'];
		$where = array('profit_state' => 1, 'profit_pay' => 0, 'profit_agent_id' => $pid);
		$list = Db::name('AgentProfit')
			->where($where)
			->where($map)
			->paginate(10, false, ['query' => $keywords]);

		foreach ($list as $k => $v) {
			$data = array();
			$data = $v;
			$account = Db::name('user')->where(['user_id' => $data['profit_uid']])->value('user_account');

			$data['profit_uid'] = getUser($data['profit_uid'], 'user_name') . '[' . $account . ']';

			if ($data['profit_type'] == 1) {
				$data['profit_type'] = '还款';
			} else if ($data['profit_type'] == 2) {
				$data['profit_type'] = '收款分润';
			} else if ($data['profit_type'] == 3) {
				$data['profit_type'] = '普通用户激活';
			} else if ($data['profit_type'] == 4) {
				$data['profit_type'] = '升级';
			}
			$data['profit_time'] = date('Y-m-d H:i:s', $data['profit_time']);
			switch ($data['profit_pay']) {
				case 0:
					$data['profit_pay'] = "未结算";
					break;
				case 1:
					$data['profit_pay'] = "已结算";
					break;
				case 2:
					$data['profit_pay'] = "已拒绝";
					break;
				case 3:
					$data['profit_pay'] = "处理中";
					break;
				default:
			}
			$data['profit_agent_id'] = $this->getAgs($data['profit_agent_id'], 'agent_name');
			$list->offsetSet($k, $data);
		}
		if (empty($list)) {
			return json(['error' => 1, 'msg' => '获取失败']);
		}

		// 今日消费金额
		$todymoney = Db::name('AgentProfit')
			->where('profit_time', '>', strtotime(date("Y-m-d"), time()))
			->where('profit_agent_id', $pid)
			->sum('profit_amount');
		//今日分润
		$todyprofit = Db::name('AgentProfit')
			->where('profit_time', '>', strtotime(date("Y-m-d"), time()))
			->where('profit_agent_id', $pid)
			->sum('profit_money');
		//总消费额
		$sunmoney = Db::name('AgentProfit')
			->where($where)
			->where($map)
			->sum('profit_amount');
		//总分润
		$sunprofit = Db::name('AgentProfit')
			->where($where)
			->where($map)
			->sum('profit_money');

		$this->assign('todymoney', $todymoney);
		$this->assign('todyprofit', $todyprofit);
		$this->assign('sunmoney', $sunmoney);
		$this->assign('sunprofit', $sunprofit);
		$this->assign('list', $list);
		$this->assign('getdata', $keywords);
		return view();
	}

	// 分润明细 查询条件过滤
	public function getwheres($keywords)
	{
		$where = [];

		if ($keywords['profit_form_no']) {
			$where[] = ['profit_form_no', '=', $keywords['profit_form_no']];

		}
		if ($keywords['profit_type']) {
			$where[] = ['profit_type', '=', $keywords['profit_type']];
		}
		if (isset($keywords['starttime'])) {
			if (empty($keywords['endtime'])) {
				$where[] = ['profit_time', 'between time', [$keywords['starttime'], date('Y-m-d', time() + 999999)]];
			} else {
				$where[] = ['profit_time', 'between time', [$keywords['starttime'], $keywords['endtime']]];
			}

		} elseif (isset($keywords['endtime'])) {
			if (empty($keywords['starttime'])) {
				$where[] = ['profit_time', 'between time', ['1970-10-1', $keywords['endtime']]];
			} else {

			}
		}
		return $where;
	}

	// 我的分润明细
	public function perrunfine()
	{
		$member_id = session::get('member_id');
		$keywords = input('get.');
		if (isset($keywords) && !empty($keywords)) {
			$map = [];
			$map = $this->getwheres($keywords);
		}
		if ($keywords['texts']) {
			$wheres[] = array('user_name|user_phone|user_account|profit_form_no', 'like', '%' . $keywords['texts'] . "%");
		}

		$where = array('blog_user' => $member_id);
		$list = Db::name('user_bonuslog')
			->where($where)
			->order('blog_id desc')
			->paginate(10, false, ['query' => $keywords]);
		foreach ($list as $k => $v) {
			$data = array();
			$data = $v;
			if ($data['blog_type'] == 1) {
				$data['blog_type'] = '升级';
			} else if ($data['blog_type'] == 2) {
				$data['blog_type'] = '收款分润';
			} else if ($data['blog_type'] == 3) {
				$data['blog_type'] = '还款分润';
			}
			$data['blog_time'] = date('Y-m-d H:i:s', $data['blog_time']);
			$data['profit_pay'] = "已结算";
			$data['userinfo'] = Db::name('user')->where(["user_id" => $v["blog_touser"]])->field("user_name,user_account")->find();
			$list->offsetSet($k, $data);
		}
		if (empty($list)) {
			return json(['error' => 1, 'msg' => '获取失败']);
		}

		//今日消费金额
//        $todymoney = Db::name('user_bonuslog')
//        	->where('blog_time','>',strtotime(date("Y-m-d"),time()))
//        	->where('blog_user',$member_id)
//        	->sum('blog_amount');
		//今日分润
		$todyprofit = Db::name('user_bonuslog')
			->where('blog_time', '>', strtotime(date("Y-m-d"), time()))
			->where('blog_user', $member_id)
			->sum('blog_money');
		//总消费额
//	    $sunmoney = Db::name('AgentProfit')->alias('p')
//	    	->where($where)
//          	->where($wheres)
//			->where($map)
//          	->join('user u','u.user_id=p.profit_uid','LEFT')
//	    	->sum('profit_amount');
		//总分润
		$sunprofit = Db::name('user_bonuslog')
			->where('blog_user', $member_id)
			->sum('blog_money');

		//$this->assign('todymoney',$todymoney);
		$this->assign('todyprofit', $todyprofit);
		//$this->assign('sunmoney',$sunmoney);
		$this->assign('sunprofit', $sunprofit);

		$this->assign('getdata', $keywords);
		$this->assign('list', $list);

		return view();
	}

	/**
	 * 选择时间，查询时间段数据
	 */
	public function Putforwardsub()
	{
		if ($this->request->isAjax()) {
			$post = input('post.');
			if (empty($post)) {
				return json(['error' => 1, 'msg' => '请选择时间']);
			}

			$data = array();
			$data['count'] = Db::name('AgentProfit')
				->where('profit_agent_id', session::get('agent_id'))
				->where(['profit_state' => 1, 'profit_pay' => 0, 'profit_pay' => 2])
				->where('profit_time', 'between', [strtotime($post['stra']), strtotime($post['end'])])
				->count('profit_id');

			$data['sunmoney'] = Db::name('AgentProfit')
				->where('profit_agent_id', session::get('agent_id'))
				->where(['profit_state' => 1, 'profit_pay' => 0, 'profit_pay' => 2])
				->where('profit_time', 'between', [strtotime($post['stra']), strtotime($post['end'])])
				->sum('profit_money');
			return json(['error' => 0, 'msg' => 'ok', 'data' => $data]);
		} else {
			return json(['error' => 1, 'msg' => '非法请求']);
		}
	}


	// 获取代理商信息
	function getAgs($id, $fied)
	{
		if ($id == 0) return '无';
		$field = Db::name('user')->where(array('user_id' => $id))->value($fied);
		if (!$field) {
			return '无';
		}
		return $field;
	}
}